package com.xsomnus.rpc.consumer.controller;

import com.alibaba.fastjson.JSON;
import com.xsomnus.rpc.common.entity.User;
import com.xsomnus.rpc.consumer.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019-04-22 22:01
 */
@Slf4j
@RestController
public class IndexController {

    @Autowired
    IUserService userService;

    @RequestMapping("insert")
    public boolean insertUser() throws InterruptedException {
        long start = System.currentTimeMillis();

        int threadCount = 1;
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                User user = User.random();
                User result = userService.insert(user);
                log.debug("返回的插入的用户信息是: {}", JSON.toJSONString(result));
                countDownLatch.countDown();
            }).start();
        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        log.debug("线程数: {}, 执行时间: {}", threadCount, (end-start));
        return true;
    }

    @RequestMapping("getById")
    public User getById(String id) {
        return userService.getById(id);
    }

}
